package com.bee.bootstrap.token.controller;

import com.bee.bootstrap.user.service.IUserService;
import com.bee.common.core.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.NotBlank;
import org.jose4j.lang.JoseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/tokens")
@Validated
@Api(value = "/tokens", description = "鉴权管理")
public class TokenController {

	@Autowired
	private IUserService userServiceImpl;
	
	@ApiOperation(value="web端登录", notes="根据用户账号密码登录获取生成对应的token")
	@PostMapping("/web")
	public Result webToken(@RequestParam(required = false, defaultValue = "",value = "userName") @NotBlank(message = "用户名不能为空") String userName
			,@RequestParam(required = false, defaultValue = "",value = "passWord") @NotBlank(message = "密码不能为空") String passWord){
		return userServiceImpl.login(userName,passWord);
	}
	
	@ApiOperation(value="app端登录", notes="根据手机号码登录生成对应的token")
	@PostMapping("/app")
	public Result saveAppToken(
			@RequestParam(required = false, defaultValue = "",value = "phone") @NotBlank(message = "手机号码不能为空") String phone
			,@RequestParam(required = false, defaultValue = "",value = "code") @NotBlank(message = "短信验证码不允许为空") String code) throws JoseException {
		return userServiceImpl.saveAppToken(phone,code);
	}

	@ApiOperation(value="更换手机号码", notes="更换手机号码")
	@PutMapping("/phone")
	public Result updateAppToken(
			@RequestParam(required = false, defaultValue = "") @NotBlank(message = "手机号码不能为空") String phone
			,@RequestParam(required = false, defaultValue = "") @NotBlank(message = "短信验证码不允许为空") String code,HttpServletRequest request) throws JoseException {
		String token=(String)request.getAttribute("token");
		return userServiceImpl.updateAppToken(token,phone,code);
	}

	@ApiOperation(value="退出登录", notes="退出登录")
	@DeleteMapping("/remove")
	public Result deleteAppToken(HttpServletRequest request) throws JoseException {
		String token=(String)request.getAttribute("token");
		return userServiceImpl.deleteAppToken(token);
	}



	
	

}
